<template>
  <div class="elx-imgbox">
    <el-dialog
      v-model="visible"
      :title="$t('videoManager.picManager')"
      class="components-video-index"
      top="40px"
      width="900px"
      :append-to-body="visible"
      @close="handleDialogClose"
    >
      <div
        tab-position="top"
      >
        <div
          v-if="options.activeTab==='pick'"
          :label="$t('videoManager.chooseVideo')"
          class="pick-block"
        >
          <div
            v-if="isLoading"
            class="elx-img-list-loading"
          >
            <div class="el-icon-loading" />
          </div>
          <el-form
            :inline="true"
            @submit.prevent
          >
            <el-form-item>
              <el-input
                v-model="fileName"
                :placeholder="$t('videoManager.videoName')"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <div
                class="primary-btn default-btn"
                @click="searchImg"
              >
                {{ $t("videoManager.query") }}
              </div>
              <div
                v-if="options.enableUpload"
                class="default-btn primary-btn"
                style="margin-left:10px"
                @click="options.activeTab='upload'"
              >
                {{ $t("videoManager.uploadVideo") }}
              </div>
            </el-form-item>
          </el-form>
          <div class="box">
            <div class="group group-box">
              <div
                :class="['group-item',groupId === 0 ?'active': '']"
                @click="clickGroup(0)"
              >
                <span class="group-name">{{ $t("videoManager.AllVideos") }}</span>
              </div>
              <div
                v-for="item in groupList"
                :key="item.attachFileGroupId"
                :class="['group-item',groupId === item.attachFileGroupId ?'active': '']"
              >
                <span
                  class="group-name"
                  @click="clickGroup(item.attachFileGroupId)"
                >{{ item.name }}</span>
              </div>
            </div>
            <div class="img-list">
              <div class="elx-main elx-img-list">
                <div
                  v-for="(img, itemIndex) in imgRes.records"
                  :key="itemIndex"
                  class="img-item"
                >
                  <div
                    class="thumb-wp"
                    @click="onClickListImage(img)"
                  >
                    <video
                      :src="resourcesUrl + img.filePath"
                      controls="controls"
                      class="showVideo"
                      style="width:175px;height:88px;"
                    />
                  </div>
                  <div
                    class="title"
                    @click="onClickListImage(img)"
                  >
                    {{ img.fileName }}
                  </div>
                  <span
                    v-if="img.selected"
                    class="selected"
                    @click="onClickListImage(img)"
                  >
                    <span class="icon" />
                    <el-icon style="font-size:18px ; color:#ffff"><Check /></el-icon>
                  </span>
                </div>
              </div>
              <el-pagination
                layout="total, prev, pager, next"
                :current-page="imgRes.current"
                :page-size="imgRes.size"
                :total="imgRes.total"
                @update:current-page="onPageChange"
              />
            </div>
          </div>
          <div class="elx-foot">
            <el-badge
              v-if="isMultiple"
              :value="images.length"
              class="item"
            >
              <div
                class="default-btn"
                @click="visible = false"
              >
                {{ $t("resource.cancel") }}
              </div>
              <div
                :class="[images.length === 0?'disabled-btn':'','default-btn primary-btn']"
                :disabled="images.length === 0"
                style="margin-right:3px;"
                @click="onConfirm"
              >
                {{ $t("resource.confirm") }}
              </div>
            </el-badge>
            <div
              v-else
              :class="[images.length === 0?'disabled-btn':'','default-btn primary-btn']"
              :disabled="disabled"
              @click="onConfirm"
            >
              {{ $t("resource.confirm") }}
            </div>
          </div>
        </div>

        <div
          v-if="options.enableUpload&&options.activeTab==='upload'"
          :label="$t('videoManager.uploadVideo')"
          name="upload"
          class="upload-block"
        >
          <div class="elx-upload-main">
            <div class="upload-title">
              {{ $t("resource.selectGroup") }}:
            </div>
            <div class="select-group-box">
              <div class="select-group-box-item">
                {{ $t("resource.group") }}:
              </div>
              <el-select
                v-model="selectGroup"
                clearable
                :placeholder="$t('resource.selectGroup')"
                class="select-group-box-item"
              >
                <el-option
                  v-for="item in groupList"
                  :key="item.attachFileGroupId"
                  :label="item.name"
                  :value="item.attachFileGroupId"
                />
              </el-select>
              <el-button
                style="margin-left: 10px"
                link
                type="primary"
                @click="createGroup()"
              >
                {{ $t('resource.newGroup') }}
              </el-button>
            </div>
            <div class="upload-title">
              {{ $t("videoManager.selectLocalVideo") }}
            </div>
            <!-- 视频预览 -->
            <div class="upload-video-box">
              <div
                v-for="(item, index) in videoList"
                :key="index"
                class="video-preview"
              >
                <video
                  v-if="item.url"
                  class="upShowVideo"
                  :src="item.url"
                  controls="controls"
                  style="width:175px;height:88px;"
                />
                <!-- 显示查看和删除的按钮弹窗 -->
                <div
                  class="avatar-uploader-popup"
                >
                  <i
                    class="el-icon-delete"
                    @click="preDeleteVideo(index)"
                  />
                </div>
              </div>
            </div>
            <el-upload
              ref="uploadRef"
              :class="['upload-img-preview',uploadNumberLimit()?'uoloadSty':'disUoloadSty']"
              list-type="picture-card"
              action=""
              :multiple="true"
              accept="video/*"
              :auto-upload="false"
              :show-file-list="false"
              :limit="options.limit"
              :before-upload="beforeUploadVideo"
              :http-request="httpRequest"
              :on-change="onUploadChange"
              :on-exceed="onUploadExceedTip"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <div class="upload-tip">
              {{ uploadTips() }}
            </div>

            <div class="elx-upload-foot">
              <div
                class="default-btn"
                @click="options.activeTab = 'pick'"
              >
                {{ $t("shop.return") }}
              </div>
              <div
                class="primary-btn default-btn"
                @click="onUploadConfirm"
              >
                {{ $t("videoManager.confirmUpload") }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <GroupAddOrUpdate
      v-if="groupVisible"
      ref="groupAddOrUpdateRef"
      @get-group-data="getGroupList"
    />
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { Check, Plus } from '@element-plus/icons-vue'
import GroupAddOrUpdate from '@/components/group-add-or-update/index.vue'
import http, { uploadFile } from '@/utils/http.js'
const emit = defineEmits(['refreshPic'])
const resourcesUrl = import.meta.env.VITE_APP_RESOURCES_URL
// 组件ref
const uploadRef = ref(null)
const groupAddOrUpdateRef = ref(null)
const groupVisible = ref(false)
const images = ref([]) // 已选视频
let fileIds = [] // 已选视频的fileId

const options = reactive({
  multiple: true, // 是否支持选取多个视频
  limit: 20, // 最多可选择视频数量
  maxSize: 2, // 最大尺寸（M）
  activeTab: 'pick',
  enableUpload: true, // 是否启用视频上传
  callback: null
})
let uploadFileNum = 0

const groupList = ref([]) // 分组列表
const selectGroup = ref('')
const isMultiple = ref(false) // 是否支持选取多个视频
const fileName = ref('')
const isLoading = ref(true)
const visible = ref(false)
const disabled = ref(false)
const imgRes = ref({
  current: 1,
  size: 5,
  total: 0
})
const videoList = ref([])
const groupId = ref(0) // 点击分组

let isSubmit = false

watch(
  () => options.activeTab,
  (val) => {
    fileName.value = ''
    if (val === 'pick') {
      loadListImage(1)
    }
  }, { deep: true }
)

/**
 * 初始化
 * type 1：单  2：多
 */
const init = (typeParams) => {
  visible.value = true
  isLoading.value = false
  images.value = []
  fileIds = []
  if (typeParams === 1) {
    isMultiple.value = false
    disabled.value = true
  } else {
    isMultiple.value = true
  }
  if (uploadRef.value) {
    uploadRef.value.uploadFiles = []
  }
  // 获取产品数据 - 第一页的数据
  loadListImage(1)
  getGroupList()
}

const onConfirm = () => {
  if (!isMultiple.value) {
    nextTick(() => {
      emit('refreshPic', images.value[0].filePath)
    })
  } else {
    const imgPaths = images.value.map(file => {
      return file.filePath
    }).join(',')
    emit('refreshPic', imgPaths)
  }
  visible.value = false
}

/**
 * 点击视频时选中或取消选中视频
 * @param img object
 */
const onClickListImage = (img) => {
  // 单选图片
  if (!isMultiple.value) {
    clearListSelected()
    images.value = []
    fileIds = []
    disabled.value = false
  } else {
    // 多选图片-如果已选中则取消选中
    const imgIndex = selectedImageIndex(img)
    if (imgIndex >= 0) {
      // 取消图片已选状态
      img.selected = false
      images.value.splice(imgIndex, 1)
      fileIds.splice(imgIndex, 1)
      return
    }
  }
  if (!isMultiple.value && !uploadNumberLimit()) {
    message($t('pictureManager.superiorLimit'))
    return false
  }
  images.value.push(JSON.parse(JSON.stringify(img)))
  fileIds.push(img.fileId)
  img.selected = true
}
/**
 * 清除所有已点击视频样式
 */
const clearListSelected = () => {
  if (!isMultiple.value) {
    const list = imgRes.value.records
    list.forEach(element => {
      element.selected = false
    })
  }
}
/**
     * 按视频名称搜索视频
     */
const searchImg = () => {
  loadListImage(1)
}
// 加载视频列表数据
const loadListImage = (current) => {
  isLoading.value = true
  http({
    url: http.adornUrl('/admin/file/attachFilePage'),
    method: 'get',
    params: http.adornParams({
      current,
      size: 9,
      fileName: fileName.value || null,
      attachFileGroupId: groupId.value,
      type: 2
    })
  }).then(({ data }) => {
    imgRes.value = data
    imgRes.value.records.forEach(img => {
      fileIds.some(item => img.fileId === item) ? img.selected = true : img.selected = false
    })

    isLoading.value = false
  })
}

/**
 * 视频已选则返回下标，未选则返回-1
 */
const selectedImageIndex = (img) => {
  for (let i = 0; i < images.value.length; i++) {
    const selectedImg = images.value[i]
    if (selectedImg.fileId === img.fileId) {
      return i
    }
  }
  return -1
}

/**
 * 分页页面变化时刷新数据
 * @param page
 */
const onPageChange = (page) => {
  loadListImage(page)
}
/**
 * 获取分组列表
 */
const getGroupList = () => {
  groupVisible.value = false
  http({
    url: http.adornUrl('/admin/fileGroup/list'),
    method: 'get',
    params: {
      type: 2 // 1、视频 2、视频 3、文件
    }
  }).then(res => {
    groupList.value = res.data
  })
}
/**
 * 点击分组
 */
const clickGroup = (id) => {
  groupId.value = id
  loadListImage(1)
}
/**
 * 提交上传
 */
const onUploadConfirm = () => {
  isSubmit = true
  fileIds = []
  uploadRef.value?.submit()
}

// 新建分组
const createGroup = () => {
  groupVisible.value = true
  nextTick(() => {
    groupAddOrUpdateRef.value.show(2)
  })
}
/**
 * 上传视频
 */
const httpRequest = (event) => {
  videoList.value.forEach(item => {
    if (item.uid === event.file.uid) {
      uploadFileVideo(event)
    }
  })
}
let resData = []
const uploadFileVideo = (event) => {
  const file = event.file
  http({
    url: http.adornUrl('/admin/file/getPreSignUrl'),
    method: 'get',
    params: http.adornParams({
      fileName: file.name,
      isImFile: false
    })
  }).then(async ({ data }) => {
    await uploadFile.then(() => {
      resData.push({ fileId: data.fileId, attachFileGroupId: selectGroup.value, fileSize: file.size, type: 2 })
    })
    if (resData.length === uploadFileNum) {
      http({
        url: http.adornUrl('/admin/file/uploadSuccess'),
        method: 'put',
        data: resData
      }).then(() => {
        resData = []
        images.value = []
        fileIds = []
        event.onSuccess(data.fileId)
        disabled.value = true
        uploadRef.value.uploadFiles = []
        options.activeTab = 'pick'
        setTimeout(() => {
          isSubmit = false
          videoList.value = []
        })
        loadListImage(1)
      }).catch((err) => {
        message($t('videoManager.requestError'), true)
        throw err
      })
    }
  })
}
// 视频预上传
const onUploadChange = (file) => {
  if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb'].indexOf(file.raw.type) === -1) {
    ElMessage.error('请上传正确的视频格式')
    return false
  }
  if (isSubmit) {
    return
  }
  const showVideoList = document.querySelectorAll('.upShowVideo')
  const videoSrc = URL.createObjectURL(file.raw)
  videoList.value.push({ url: videoSrc, uid: file.uid })
  showVideoList.forEach((item) => {
    if (!item.paused) item.pause()
  })
}
// 删除预览视频
const preDeleteVideo = (index) => {
  uploadRef.value?.uploadFiles.splice(index, 1)
  videoList.value.splice(index, 1)
}
/**
 * 上传视频前检查合法性
 * @param file
 * @returns {boolean}
 */
const beforeUploadVideo = (file) => {
  const isLt20M = file.size / 1024 / 1024 < 20
  if (!isLt20M) {
    ElMessage.error('上传视频大小不能超过20MB哦!')
    return false
  }
  return true
}

const uploadNumberLimit = () => {
  if (!options.multiple) {
    return 1
  }
  return options.limit - images.value.length - uploadFileNum
}

const uploadTypeTip = () => {
  return $t('videoManager.onlySupported') + ' mp4/mov/wmv ' + $t('videoManager.video')
}

const uploadSizeTip = () => {
  return $t('videoManager.notExceed') + '20M'
}

const uploadTips = () => {
  const tips = [uploadTypeTip(), uploadSizeTip()]

  if (!options.multiple) {
    return tips.join('，')
  }

  if (images.value.length > 0) {
    tips.push($t('videoManager.alreadyExist') + images.value.length + $t('videoManager.unit'))
  }

  uploadFileNum = videoList.value.length
  if (uploadFileNum > 0) {
    tips.push($t('videoManager.soonUpload') + uploadFileNum + $t('videoManager.unit'))
  }
  tips.push($t('videoManager.remainder') + (options.limit - images.value.length - uploadFileNum) + $t('videoManager.unit') + $t('videoManager.upload'))

  return tips.join(',')
}

/**
 * 选择上传文件超过限制文件个数提示
 */
const onUploadExceedTip = () => {
  message($t('videoManager.maxSelect') + uploadNumberLimit() + $t('videoManager.unit') + $t('videoManager.upload'))
}
const message = (msg, isInfo) => {
  let type = 'error'
  if (isInfo) {
    type = 'info'
  }
  ElMessage({
    message: msg,
    type,
    duration: 1500
  })
}

/**
 * 关闭回调
 */
const handleDialogClose = () => {
  fileName.value = ''
}

onMounted(() => {
  getGroupList()
  loadListImage()
})

defineExpose({
  init
})
</script>

<style lang="scss" scoped>

.components-video-index {
  $bg: #fff;
  height: 100% !important;
  :deep(.el-badge)  {
    vertical-align: bottom;
  }

  :deep(.el-dialog)  {
    width: 820px;
   :deep(.el-dialog__header)  {
      border-bottom: 1px solid #e8e8e8;
    }

   :deep(.el-dialog__body)  {
      background: $bg;
    }
  }

  :deep(.el-tabs)  {
   :deep(.el-tabs__header)   {
      margin-right: 0;
      margin-top: 5px;
      :deep(.el-tabs__nav-wrap::after)  {
        background: $bg;
      }
    }
    :deep(.el-tabs__item.is-active)   {
      background: #fff;
    }
   :deep(.el-tabs--left .el-tabs__nav-wrap)  {
      padding-top: 15px;
    }

    :deep(.el-tabs__content) {
      min-height: 740px;
      // 弹窗高度
      background: #fff;
    }
  }

  .elx-foot {
    padding: 15px 0 0 10px;
    text-align: right;
    margin-right: 30px;
   :deep(.el-button)  {
      margin: 0 0 0 10px;
    }
  }
  .upload-block {
      .upload-img-preview {
        padding: 20px;

        /* 上传视频预览改为使用背景视频按比例缩放方式 */
      :deep(.el-upload--picture-card) ,
        :deep(.el-upload-list--picture-card .el-upload-list__item),
        :deep(.el-upload-list--picture-card .el-upload-list__item .wp) {
          width: 90px;
          height: 90px;
          line-height: 98px;
          background-size: cover;
          background-position: 50% 50%;
        }

      :deep(.el-upload-list--picture-card .el-upload-list__item-status-label i)   {
          margin-top: 12px;
          vertical-align: top;
        }
      }

      .upload-tip {
        padding: 0 20px;
        font-size: 13px;
        color: #999;
      }

      .upload-title {
        font-size: 16px;
        color: #666;
        padding: 20px 0 0 20px;
      }
    }
    :deep(.el-upload-list__item-actions)  {
    a {
      i {
        color: #fff;
      }
    }
  }
  .upload-video-box {
    .video-preview {
      width: 175px;
      height: 100px;
      display: inline-block;
      text-align: center;
      box-sizing: border-box;
      margin-right: 8px;
      margin-bottom: 5px;
      margin-top: 20px;
  }
  .avatar-uploader-popup{
    width: 100%;
    background: #f6f6f6;
    height: 18px;
  }
  }
  .group-box {
    height: 600px;
    min-width: 200px;
    overflow-y:auto;
    overflow-x: hidden;
  }
  .select-group-box {
    padding: 20px 0 0 20px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .select-group-box-item {
      margin-right: 10px;
    }
  }
  .box {
    display: flex;
    justify-content: flex-start;
    .group {
      min-width: 200px;
      padding: 10px;
      .group-item {
        height: 38px;
        line-height: 38px;
        padding: 0 10px;
        display: flex;
        justify-content: space-between;
        cursor:pointer;

        .group-name {
          width: 180px;
        }
      }
      .group-item:hover{
        background: #F7F7F7;
      }
      .active {
        background: #F7F7F7;
      }
    }
    .img-list {
      width: 1100px;
    }
  }
  .pick-block {
      position: relative;
      $bg: #f6f6f6;
      .elx-img-list-loading {
        position: absolute;
        top: 60px;
        z-index: 9;
        left: 0;
        right: 0;
        width: 100%;
        height: 520px;
        // 加载层高度
        background: #fff;
        text-align: center;

        .el-icon-loading {
          font-size: 50px;
          color: #409eff;
          line-height: 460px;
        }
      }

      .elx-img-list {
        padding: 10px;
        min-height: 530px;
        // 视频列表高度

        .img-item {
          $imgSize: 175px;
          $size: 179px;
          float: left;
          margin: 10px 20px 20px 10px;
          width: $imgSize;
          cursor: pointer;
          position: relative;
          font-size: 12px;
          .title {
            line-height: 24px;
            height: 24px;
            display: block;
            overflow: hidden;
            background: $bg;
            padding: 0 5px;
          }

          .title {
            line-height: 24px;
            height: 24px;
            display: block;
            overflow: hidden;
            background: $bg;
            padding: 0 5px;
          }

          .selected {
            position: absolute;
            right: -3px;
            top: -3px;
            width: $size;
            height: 143px;
            border: 3px solid #409eff;
            border-radius: 3px;
            text-align: right;
            .icon {
              background: #409eff;
              text-align: center;
              height: 24px;
              width: 24px;
              line-height: 24px;
              display: inline-block;
              font-size: 16px;
              color: #fff;
              border-radius: 0 0 0 3px;
              position: absolute;
              right: 0;
              top: 0;
            }
          }
        }

        &::after {
          content: " ";
          display: table;
          height: 0;
          clear: both;
          visibility: hidden;
        }
      }

    :deep(.el-pagination)  {
        position: relative;
        padding: 5px;
        // margin: 0 24px 0 20px;
        margin-right: 25px;
        text-align: right;
        float: none;

        * {
          background: none;
        }
      }
    }

    .elx-upload-main {
    padding-left: 70px;
    .elx-upload-foot {
      padding: 15px 0 0 10px;
      text-align: left;
    :deep(.el-button)  {
        margin: 0 0 0 10px;
      }
    }
  }
  div :deep(.el-tabs__header){
    display: none !important;
  }

  div :deep(.el-pagination){
    padding: 5px;
    margin-right: 25px;
    justify-content: flex-end;
  }
}

</style>>
